package day01;

import java.util.Arrays;
import java.util.Random;

/**
 * @author wang hao
 * @date 2023-02-12 18:22
 *
 *  三路快速排序算法
 */
public class QuickSort4 {

    public static void sort(int[] arr){
        Random random = new Random();
        sort(arr, 0, arr.length - 1,random);
    }

    public static void sort(int[] arr, int l, int r,Random rnd){
        if (l >= r) return;

        // 生成 [l, r]
        int p = rnd.nextInt(r - l + 1) + l;
        swap(arr, l, p);

        // arr[l+1, lt] < v  arr[lt+1, i-1] == v   arr[gt, r] > v
        int lt = l, i = l + 1, gt = r + 1;

        while (i < gt){
            if (arr[i] < arr[l]){
                lt++;
                swap(arr, i, lt);
                i++;
            }else if (arr[i] > arr[l]){
                gt--;
                swap(arr, i, gt);
            }else {
                i++;
            }
        }
        swap(arr, l, lt);

        sort(arr, l, lt - 1, rnd);
        sort(arr, gt, r, rnd);
    }

    private static void swap(int[] arr, int i, int j) {
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }


    public static void main(String[] args) {
        int[] arr = new int[]{3,7,9,4,6,1,2,8,9,12,11};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
